package com.forum.demo.services.impl;

import ch.qos.logback.core.util.StringUtil;
import com.forum.demo.common.ResultCode;
import com.forum.demo.mapper.ArticleReplyMapper;
import com.forum.demo.model.ArticleReply;
import com.forum.demo.model.response.ArticleReplyResponse;
import com.forum.demo.services.IArticleReplyService;
import com.forum.demo.utils.checkFailUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Autowired
    private ArticleServiceImpl articleService;
    @Override
    public void create(ArticleReply articleReply) {
        if (articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtil.isNullOrEmpty(articleReply.getContent())) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        int row = articleReplyMapper.insert(articleReply);
        if (row != 1) {
            checkFailUtils.checkFail(ResultCode.ERROR_SERVICES);
        }
        // 更新帖子表中的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
    }

    @Override
    public List<ArticleReplyResponse> selectByArticleId(Long articleId) {
        if (articleId == null || articleId <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        List<ArticleReplyResponse> ArticleReplys = articleReplyMapper.selectArticleReply(articleId);
        return ArticleReplys;
    }
}
